<template>
  <div class="app-container">
    <div class="space">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="通过角色名称进行模糊搜索"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="修改时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-if="addMenu"
            >新增</el-button
          >
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList">
      <el-table-column
        label="角色名称"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="描述"
        prop="introduce"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="最新修改时间" align="left" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width">
        <template
          slot-scope="scope"
          v-if="scope.row.id != 11 && scope.row.id != 12"
        >
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="updateMenu"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-if="delMenu"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入角色名称"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="introduce">
          <el-input v-model="form.introduce" maxlength="30" show-word-limit />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="form.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRole, delRole, addRole } from "@/api/system/role";
import { mapGetters } from "vuex";
import { getUserProfile } from "@/api/system/user";
export default {
  name: "Role",
  computed: {
    ...mapGetters(["menuIds"]),
    addMenu() {
      return this.menuIds.includes("4011");
    },
    updateMenu() {
      return this.menuIds.includes("4012");
    },
    delMenu() {
      return this.menuIds.includes("4013");
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      menuExpand: true,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [
        {
          id: "1",
          label: "提现管理",
          children: [
            {
              id: "100",
              label: "处理中",
              children: [
                {
                  id: "1001",
                  label: "处理",
                },
              ],
            },
            {
              id: "101",
              label: "已处理",
            },
          ],
        },
        {
          id: "2",
          label: "门店管理",
          children: [
            {
              id: "200",
              label: "新增门店",
            },
            {
              id: "201",
              label: "门店人员管理",
            },
            {
              id: "202",
              label: "修改",
            },
          ],
        },
        {
          id: "3",
          label: "会员管理",
          children: [
            {
              id: "300",
              label: "会员用户管理",
              children: [
                {
                  id: "3001",
                  label: "会员用户详情",
                },
              ],
            },
            {
              id: "301",
              label: "会员支付订单管理",
            },
          ],
        },
        {
          id: "4",
          label: "系统管理",
          children: [
            {
              id: "400",
              label: "系统用户管理",
              children: [
                {
                  id: "4001",
                  label: "新增",
                },
                {
                  id: "4002",
                  label: "修改",
                },
                {
                  id: "4003",
                  label: "重置密码",
                },
              ],
            },
            {
              id: "401",
              label: "角色管理",
              children: [
                {
                  id: "4011",
                  label: "新增",
                },
                {
                  id: "4012",
                  label: "修改",
                },
                {
                  id: "4013",
                  label: "删除",
                },
              ],
            },
            {
              id: "402",
              label: "分润比例管理",
              children: [
                {
                  id: "4021",
                  label: "修改",
                },
              ],
            },
          ],
        },
      ],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    getUserProfile({ userId: localStorage.getItem("userId") }).then(
      (response) => {
        const menuIds = JSON.parse(response.data.role.menuIds);
        this.menuOptions = this.filterMenuByIds(this.menuOptions, menuIds);
      }
    );
  },
  methods: {
    filterMenuByIds(menuOptions, menuIds) {
      return menuOptions
        .map((menu) => {
          // 深拷贝当前菜单
          const currentMenu = { ...menu };

          // 检查当前菜单 ID 是否在目标数组中
          if (menuIds.includes(currentMenu.id)) {
            // 如果有子菜单，递归处理子菜单
            if (currentMenu.children) {
              currentMenu.children = this.filterMenuByIds(
                currentMenu.children,
                menuIds
              );
            }
            return currentMenu;
          }

          // 如果当前菜单不匹配，但子菜单可能匹配
          if (currentMenu.children) {
            const filteredChildren = this.filterMenuByIds(
              currentMenu.children,
              menuIds
            );
            if (filteredChildren.length > 0) {
              currentMenu.children = filteredChildren;
              return currentMenu;
            }
          }

          // 如果当前菜单和子菜单都不匹配，返回 null
          return null;
        })
        .filter((menu) => menu !== null); // 过滤掉不匹配的菜单
    },
    /** 查询角色列表 */
    getList() {
      const data = {
        ...this.queryParams,
        startTime: this.dateRange && new Date(this.dateRange[0]).getTime(),
        endTime: this.dateRange && new Date(this.dateRange[1]).getTime(),
      };
      this.loading = true;
      listRole(data).then((response) => {
        this.roleList = response.data.records;
        this.total = response.data.total || 0;
        this.loading = false;
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          id: undefined,
          name: undefined,
          introduce: undefined,
          menuIds: [],
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      this.form.menuCheckStrictly = value ? true : false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const roleMenu = JSON.parse(row.menuIds);
      this.form = row;
      this.open = true;
      roleMenu.forEach((v) => {
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v, true, false);
        });
      });
      this.title = "修改角色";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.menuIds = JSON.stringify(this.getMenuAllCheckedKeys());
          addRole(this.form).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.id;
      this.$modal
        .confirm("是否确认删除该角色？")
        .then(function () {
          return delRole({ id: roleIds });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
